package com.zelin.gulimall.product.config;


import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Created by WF on 2021/1/16 20:42
 */
@Configuration
@EnableCaching   //开启springcache功能
@EnableConfigurationProperties(CacheProperties.class) //让自定义配置起作用
public class MyCacheConfig {

    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //序列化的关键两句
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        //下面的设置主要是application.properties中设置生效
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive()); //设置到期时间
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix()); //设置缓冲key的前缀
        }
        if (!redisProperties.isCacheNullValues()) {                     //是否可以缓冲空值，用于解决redis穿透问题
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {                        //是否启用缓冲key的前缀，没有设置就禁用
            config = config.disableKeyPrefix();
        }

        return config;
    }
}
